package com.zygh.lz.controller;

import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import com.alibaba.excel.EasyExcel;
import com.zygh.lz.entity.Sptype;
import com.zygh.lz.entity.Xlevelservice;
import com.zygh.lz.service.SptypeService;
import com.zygh.lz.service.XlevelserviceService;
import com.zygh.lz.stapprove.ResultUtil;
import com.zygh.lz.stapprove.SysPcLog;
import com.zygh.lz.vo.ResultBean;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import jxl.Workbook;
import jxl.format.UnderlineStyle;
import jxl.write.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Api(tags = "特殊勤务类", description = "xlevelserviceController")
@RestController
public class XlevelserviceController {
    Log log = LogFactory.get();

    @Value("${file.download.templet}")
    private String path;
    @Resource
    private XlevelserviceService xlevelserviceService;

    @Resource
    private SptypeService sptypeService;


    @ApiOperation("特殊勤务》导出勤务报表")
    @RequestMapping(value = "exportPersonServiceExcel", method = RequestMethod.GET)  //导出勤务报表
    @ResponseBody
    public void exportPersonServiceExcel(HttpServletResponse response, Integer type) throws Exception {
        String property = System.getProperty("user.dir") + "\\Excel\\";

        File file1 = new File(property);
        if (!file1.exists()) {
            file1.mkdirs();
        }

        String fileName = UUID.randomUUID().toString() + "特殊勤务.xls";

        File file = new File(property + fileName);

        try {
            file.createNewFile();
            WritableWorkbook wwb = Workbook.createWorkbook(file);


            //start设置每列的宽度
            WritableSheet ws = wwb.createSheet("sheet1", 0);

            //给sheet电子版中所有的列设置默认的列的宽度;
            ws.getSettings().setDefaultColumnWidth(8);

            //分别给列设置不同的宽度;
            ws.setColumnView(0, 20);

            List<Sptype> sptypeList ;
            List<Xlevelservice> xlevelserviceList ;

            sptypeList = sptypeService.selectSptypeInfo(type);
            xlevelserviceList = xlevelserviceService.selectXlevelservice(sptypeList.get(0).getLx());


            //start 合并单元格（左上列，左上行，右下列，右下行）
            ws.mergeCells(0, 0, 0, 0);
            Label sheetTitle = new Label(0, 0, "特殊勤务", getHeaderCellStyle(12));
            ws.addCell(sheetTitle);

            //（列，行）
            Label sheetTitle2 = new Label(0, 1, "勤务名称", getHeaderCellStyle(10));
            ws.addCell(sheetTitle2);

            //（列，行）
            Label sheetTitle3 = new Label(1, 1, "勤务管辖区域", getHeaderCellStyle(10));
            ws.addCell(sheetTitle3);

            //列，行
            Label sheetTitle4 = new Label(2, 1, "执勤时间", getHeaderCellStyle(10));
            ws.addCell(sheetTitle4);

            //列，行
            Label sheetTitle5 = new Label(3, 1, "警力人数", getHeaderCellStyle(10));
            ws.addCell(sheetTitle5);

            int c = 0;
            for (int i = 0; i < xlevelserviceList.size(); i++) {
                int h = i + 2;
                c++;

                if (type >= 0) {
                    String zdname = null;
                    int state = xlevelserviceList.get(i).getState();
                    if (state == 0) {
                        zdname = "等级勤务";
                    } else if (state == 1) {
                        zdname = "重要警卫任务";
                    } else if (state == 2) {
                        zdname = "应急管理任务";
                    } else if (state == 3) {
                        zdname = "专项警卫任务";
                    } else if (state == 4) {
                        zdname = "大型活动";
                    } else {
                        zdname = "其他";
                    }
                    Label name = new Label(0, h, zdname, getHeaderCellStyle(10));
                    ws.addCell(name);
                    //勤务名称
                    Label count1 = new Label(1, h, xlevelserviceList.get(i).getCallsign() + "", getHeaderCellStyle(11));
                    ws.addCell(count1);
                    //勤务管辖区域
                    Label count2 = new Label(2, h, xlevelserviceList.get(i).getPlace() + "", getHeaderCellStyle(11));
                    ws.addCell(count2);
                    //执勤时间
                    //执勤人数
                    Label count4 = new Label(3, h, xlevelserviceList.get(i).getNumber() + "", getHeaderCellStyle(11));
                    ws.addCell(count4);
                }

            }


            for (int i = 0; i <= c; i++) {
                //            行数    高
                ws.setRowView(i, 400, false); //设置行高
            }
            wwb.write();
            wwb.close();

            //获取要下载的文件名
            String excelName = fileName;

            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            //设置content-disposition响应头控制浏览器以下载的形式打开文件
            response.addHeader("Content-Disposition", "attachment;filename=" + excelName);

            //获取要下载的文件的绝对路径
            String realPath = property + fileName;

            InputStream in = null;
            OutputStream out = null;
            try {
                //获取要下载的文件输入流
                in = new FileInputStream(realPath);
                int len = 0;
                //创建数据缓冲区
                byte[] buffer = new byte[1024];
                //通过response对象获取outputStream流
                out = response.getOutputStream();
                //将FileInputStream流写入到buffer缓冲区
                while ((len = in.read(buffer)) > 0) {
                    //使用OutputStream将缓冲区的数据输出到浏览器
                    out.write(buffer, 0, len);
                }
                out.flush();
                in.close();
            } catch (Exception e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            } finally {
                if (out != null) {
                    try {
                        out.close();
                    } catch (IOException e1) {
                        e1.printStackTrace();
                    }
                }
            }
        } catch (Exception e) {
            System.out.println(e.toString());
            throw e;

        }
    }

    /**
     * 表头单元格样式的设定 单元格为黑色
     */
    private WritableCellFormat getHeaderCellStyle(int a) {
        WritableFont font = new WritableFont(WritableFont.createFont("宋体"),
                a,
                WritableFont.NO_BOLD,
                false,
                UnderlineStyle.NO_UNDERLINE);

        WritableCellFormat headerFormat = new WritableCellFormat(NumberFormats.TEXT);
        try {
            headerFormat.setFont(font);
            headerFormat.setBorder(Border.ALL, BorderLineStyle.THIN, Colour.BLACK);
            headerFormat.setAlignment(jxl.format.Alignment.CENTRE);// 单元格内容水平居中
            headerFormat.setVerticalAlignment(VerticalAlignment.CENTRE); //设置垂直对齐
        } catch (WriteException e) {

        }
        return headerFormat;
    }


    @ApiOperation("PC勤务树状结构")
    @GetMapping("/findTree")
    public ResultBean findTree() {
        List<Map> trees = xlevelserviceService.findTree();
        return ResultUtil.setOK("success", trees);
    }

    @ApiOperation("查看包含禁用的勤务树状结构")
    @GetMapping("/find/tree")
    public ResultBean findtree(){
        List<Map> trees = xlevelserviceService.findtree();
        return ResultUtil.setOK("success", trees);
    }
    @ApiOperation("删除特殊勤务")
    @GetMapping("delSpecialService")
    //@SysPcLog(module = "删除特殊勤务",operation = "删除")
    public ResultBean delSpecialService(Integer id) {
        return xlevelserviceService.delSpecialService(id);
    }


    @ApiOperation("查询岗位下的人员")
    @GetMapping("/find/people")
    public ResultBean findPeople(HttpServletRequest request, Integer positionId) {
        return xlevelserviceService.findPeople(request,positionId);
    }

    @ApiOperation("修改特殊勤务")
    @GetMapping("updateSpecialService")
    //@SysPcLog(module = "修改特殊勤务",operation = "修改")
    public ResultBean updateSpecialService(Xlevelservice xlevelservice) {
        return xlevelserviceService.updateSpecialService(xlevelservice);
    }

    @ApiOperation("新增特殊勤务树")
    @PostMapping("/addSpecialServiceTree")
    @SysPcLog(module = "新增特殊勤务树",operation = "新增")
    public ResultBean addSpecialServiceTree(@RequestBody Xlevelservice xlevelservice) {
        return xlevelserviceService.addSpecialServiceTree(xlevelservice);
    }

    @ApiOperation("修改特殊勤务树")
    @PostMapping("/updateSpecialServiceTree")
    //@SysPcLog(module = "修改特殊勤务树",operation = "修改")
    public ResultBean updateSpecialServiceTree(@RequestBody Xlevelservice xlevelservice) {
        return xlevelserviceService.updateSpecialServiceTree(xlevelservice);
    }

    @ApiOperation("警力部署树状结构")
    @GetMapping("/police/distribute")
    public ResultBean policeDistribute() {
        return xlevelserviceService.policeDistribute();
    }

    @ApiOperation("警力部署详情")
    @GetMapping("/police/detail")
    public ResultBean policeDetail(Integer positionId) {
        return xlevelserviceService.policeDetail(positionId);
    }

    @ApiOperation("在线警力")
    @GetMapping("/police/now")
    public ResultBean policeNow(Integer positionId, Integer deptId) {
        return xlevelserviceService.policeNow(positionId, deptId);
    }

    @ApiOperation("导入excel")
    @PostMapping("/import/excel")
    public ResultBean importExcel(MultipartFile file)  {
        try {
            List<Xlevelservice> result = EasyExcel.read(file.getInputStream()).head(Xlevelservice.class).sheet().doReadSync();

            return xlevelserviceService.insertAll(result);
        }catch (Exception e){
            log.error("导入特殊勤务excel异常",e);
        }
        return ResultUtil.setError(500,"导入请和平台类型保持一致",null);
    }
    /**
     * @param response
     * @功能描述 下载文件:
     */
    @RequestMapping("/download")
    public void download( HttpServletResponse response) {

        try {
            // path是指想要下载的文件的路径
            File file = new File(path);
            log.info(file.getPath());
            // 获取文件名
            String filename = file.getName();
            // 获取文件后缀名
            String ext = filename.substring(filename.lastIndexOf(".") + 1).toLowerCase();
            log.info("文件后缀名：" + ext);
            // 将文件写入输入流
            FileInputStream fileInputStream = new FileInputStream(file);
            InputStream fis = new BufferedInputStream(fileInputStream);
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            // 清空response
            response.reset();
            //Content-Disposition的作用：告知浏览器以何种方式显示响应返回的文件，用浏览器打开还是以附件的形式下载到本地保存
            //attachment表示以附件方式下载   inline表示在线打开   "Content-Disposition: inline; filename=文件名.mp3"
            // filename表示文件的默认名称，因为网络传输只支持URL编码的相关支付，因此需要将文件名URL编码后进行传输,前端收到后需要反编码才能获取到真正的名称
              // 告知浏览器文件的大小
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
            response.setHeader("Content-Disposition",
                    "attachment;filename=\"" +URLEncoder.encode(filename,"utf8")  + "\"");
            OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
            outputStream.write(buffer);
            outputStream.flush();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

}


